package com.test.controller;

import com.google.code.kaptcha.Producer;
import com.test.utils.CreateKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;

@RestController
@RequestMapping("/producer")
public class KaptchaController {
    @Autowired
    private Producer producer;
    @RequestMapping("/kaptcha")
    public void produceKaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception{
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        System.out.println(text);
        /**
         *在此处做text的缓存，方便登陆校验
         * 例如：HttpSession session=re.getSession();
         *     session.setAttribute("code", sb.toString());
         **/
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image,"jpg",out);
    }

    @RequestMapping("/selfdefinitionkaptcha")
    public void selfDefinitionKaptcha(HttpServletResponse response,HttpSession session ) throws Exception{
        Object[] objs = CreateKaptcha.createImage();
        String text = (String) objs[0];
        //将验证码放入到session中进行比对
        session.setAttribute("checkCode",text);
        /**
         * 缓存验证码
         *ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
         */
        BufferedImage image =
                (BufferedImage) objs[1];
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "png", out);

    }

}
